<template>
    <div class="main-content">
        <echartsLayout :formState='formState' :dataListState='dataListState' :eCharts1State='eCharts1State' :eCharts2State='eCharts2State' 
        :eCharts3State='eCharts3State' :chartsListState='chartsListState' :tableState='tableState'>
            <div slot="form">
                <el-form :model="query" ref="query" label-width="70px" label-position="right">
                    <el-row :gutter="41">
                       <el-col :span="7">
                            <el-form-item label="省份" prop="provinceId">
                                <province v-model="query.provinceId" :name.sync="query.provinceName"></province>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="市区" prop="cityId">
                                <city v-model="query.cityId" :province="query.provinceId" :name.sync="query.cityName"></city>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="区县" prop="areaId">
                                <region v-model="query.areaId" :city="query.cityId" :name.sync="query.areaName"></region>
                            </el-form-item>
                        </el-col>
                    </el-row> 
                    <el-row :gutter="41">
                        <el-col :span="7">
                            <el-form-item label="时间范围" prop="timeRange"> 
                               <el-select v-model="query.timeRange" placeholder="请选择" style="width:100%">
                                    <el-option v-for="item in timeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3" :offset="14">
                            <div class="top-line">
                                <el-button type="primary" class="btn-common" @click="onSubmit">查询</el-button>
                            </div>
                        </el-col>
                    </el-row> 
                </el-form>
            </div> 
            <div slot="eCharts1" >
                <div class="charts-title">积分支出对比图</div>
                <div class="charts-display" v-loading='chart1Loading'>
                    <trendChart width='100%' height='100%' id="trendChart1" :option='trendChart1Option'></trendChart>
                </div>
            </div>
            <div slot="eCharts2" >
                <div class="charts-title">积分获取对比图</div>
                <div class="charts-display" v-loading='chart2Loading'>
                   <trendChart width='100%' height='100%' id="trendChart2" :option='trendChart2Option'></trendChart>
                </div>
            </div>
            <div slot="eCharts3" >
                <div class="charts-title">积分消耗对比图</div>
                <div class="charts-display" v-loading='chart3Loading'>
                   <trendChart width='100%' height='100%' id="trendChart3" :option='trendChart3Option'></trendChart>
                </div>
            </div>
        </echartsLayout>
    </div>
</template>

<script>
    import moment from 'moment';
    import province from 'components/CascadeRegion/province';
    import city from 'components/CascadeRegion/city';
    import region from 'components/CascadeRegion/region';
    import echartsLayout from 'components/TableLayout/echartsLayout'; 
    import trendChart from 'components/Charts/trendChart';
    import { queryTable } from 'api/common';
    export default{
        name: 'integralChart',
        components: {province, city, region, echartsLayout, trendChart},
        data() {
            return {
                chart1Loading: false,
                chart2Loading: false,
                chart3Loading: false,
                formState: false,
                dataListState: true,
                eCharts1State: false,
                eCharts2State: false,
                eCharts3State: false,
                chartsListState: true,
                tableState: true,
                timeList: [{
                    value: '本月',
                    label: '本月'
                }, {
                    value: '三个月',
                    label: '三个月'
                }, {
                    value: '半年内',
                    label: '半年内'
                }, {
                    value: '本年',
                    label: '本年'
                }],
                query: {
                    provinceId: '',
                    cityId: '',
                    areaId: '',
                    provinceName: '',
                    cityName: '',
                    areaName: '',
                    timeRange: '本月',
                    startData: moment(new Date()).format('YYYY-MM-01'),
                    endData: moment(new Date()).format('YYYY-MM-DD'),
                    unit: 'day'
                },
                trendChart1Option: null,
                trendChart2Option: null,
                trendChart3Option: null,
                filterList: null,
                resState: false
            }
        },
        computed: {
           
        },
        created() {
            this.queryData();
        },
        methods: {
            // getProvinceName(provinceName) {
            //     this.query.provinceName = provinceName;
            // },
            // getCityName(cityName) {
            //     this.query.cityName = cityName;
            // },
            // getAreaName(areaName) {
            //     this.query.areaName = areaName;
            // },
            queryData() {
                this.getTrendChart1();
                this.getTrendChart2();
                this.getTrendChart3();
            },
            onSubmit() {

                this.query.endData = moment(new Date()).format('YYYY-MM-DD');
                if (this.query.timeRange == '本月') {
                    this.query.unit = 'day';
                    this.query.startData = moment(new Date()).format('YYYY-MM-01');
                } else if (this.query.timeRange == '三个月') {
                    this.query.unit = 'month';
                    this.query.startData = moment(new Date()).month(-2).format('YYYY-MM-DD');
                } else if (this.query.timeRange == '半年内') {
                    this.query.unit = 'month';
                    this.query.startData = moment(new Date()).month(-5).format('YYYY-MM-DD');
                } else if (this.query.timeRange == '本年') {
                    this.query.unit = 'month';
                    this.query.startData = moment(new Date()).format('YYYY-01-01');
                } else {
                    this.query.unit = 'day';
                    this.query.startData = moment(new Date()).format('YYYY-MM-01');
                }

                let conditionsList = [];
                if (this.query.provinceName) {
                    conditionsList.push({'field': 'user.province', 'function': 'equal', 'params': [this.query.provinceName]});
                }
                if (this.query.cityName) {
                    conditionsList.push({'field': 'user.city', 'function': 'equal', 'params': [this.query.cityName]});
                }
                if (this.query.areaName) {
                    conditionsList.push({'field': 'user.area', 'function': 'equal', 'params': [this.query.areaName]});
                }
                this.filterList = {};
                if (conditionsList.length == 1) {
                    this.filterList = {'conditions': conditionsList};
                } else if (conditionsList.length > 1) {
                    this.filterList = {'relation': 'and', 'conditions': conditionsList};
                } else {
                    this.filterList = {};
                }

                this.queryData();
            },
            getTrendChart1() {
                // 平台支出总量
                let totalPlatform = [];
                let query_id = 79;
                let show_list = false;
                let real_time = false;
                let type = 'event';
                let query1 = {
                    'province': this.query.provinceName,
                    'city': this.query.cityName,
                    'area': this.query.areaName,
                    'from_date': this.query.startData,
                    'to_date': this.query.endData
                };
               
                let query = {
                    'measures': [{'event_name': 'getPoint', 'aggregator': 'SUM', 'field': 'event.getPoint.pointNum'}], 'unit': this.query.unit, 
                    'filter': this.filterList, 
                    'sampling_factor': 64, 'from_date': this.query.startData, 'to_date': this.query.endData, 'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515752447784
                };
                
                let inforSent = {
                    query_id: 80,
                    real_time: true,
                    type: 'line',
                    query
                };
                
                let legendList1 = [];
                let xAxisDataList = [];
                this.chart1Loading = true;
                queryTable(query1, query_id, undefined, undefined, show_list, type, real_time).then(response => {
                    
                    let dataList = response.data.content.rows;
                    let dataTotal = 0;
                    dataList.forEach(item => {
                        totalPlatform.push(item.s_score);
                        if (item.date.length == 2) {
                            if (this.query.unit == 'month') {
                                this.resState = true;
                                item.date = moment(this.query.startData).format('YYYY-MM');
                            } else {
                                this.resState = false;
                                item.date = moment(this.query.startData).format('MM') + '-' + item.date;
                            }
                        }
                        dataTotal = dataTotal + item.s_score;
                        legendList1.push(item.date);
                    })
                    
                    // 积分图表统计——用户获取量
                    this.$store.dispatch('getQuery', inforSent).then((data) => {
                        this.chart1Loading = false;
                        let rows = data.data.detail_result.rows;
                        let userTotal = [];
                        rows.forEach((item, s) => {
                            for (let i=0;i<item.values.length;i++) {
                                if (isNaN(userTotal[i])) {
                                    userTotal[i] = 0;
                                }
                                userTotal[i] = Number(userTotal[i])+Number(item.values[i]); 
                            }
                        });

                        let arrayList = [...data.xAxisData, ...legendList1].sort();
                    
                        for (let i=0; i < arrayList.length; i++) {
                            if (!xAxisDataList.includes(arrayList[i])) {
                                xAxisDataList.push(arrayList[i]);
                            }
                        }

                        let xAxisDataIndex = 0;
                        let watchIndex = 0;
                        let buyTotalList = []; // 平台支出总量
                        let seeTotalList = []; // 用户获取总量
                        xAxisDataList.forEach((item, index) => {
                            if (this.resState) {
                                buyTotalList.push(dataTotal);
                            } else {
                                if (legendList1[xAxisDataIndex] == item) {
                                    buyTotalList.push(totalPlatform[xAxisDataIndex]);
                                    xAxisDataIndex++;
                                } else {
                                    buyTotalList.push(0);
                                }
                            }
                            
                            if (data.xAxisData[watchIndex] == item) {
                                seeTotalList.push(userTotal[watchIndex]);
                                watchIndex++;
                            } else {
                                seeTotalList.push(0);
                            }

                        })
                        
                        this.trendChart1Option = {
                            color: ['#B6A2DE', '#2EC7C9'],
                            tooltip: {
                                trigger: 'axis'
                            },
                            legend: {
                                data: ['用户获取总量', '平台支出总量']
                            },
                            calculable: true,
                            xAxis: [
                                {
                                    type: 'category',
                                    boundaryGap: false,
                                    data: xAxisDataList // data.xAxisData // ['一月', '二月', '三月', '四月', '五月', '六月']
                                }
                            ],
                            yAxis: [
                                {
                                    type: 'value'
                                }
                            ],
                            series: [
                                {
                                    name: '用户获取总量',
                                    type: 'line',
                                    stack: '总量',
                                    data: seeTotalList // userTotal 
                                },
                                {
                                    name: '平台支出总量',
                                    type: 'line',
                                    stack: '总量',
                                    data: buyTotalList // totalPlatform
                                }
                            ]
                        };
                    }).catch(() => {
                        this.chart1Loading = false;
                    });
                }).catch(() => {
                    this.chart1Loading = false;
                });
            },
            getTrendChart2() {
               
                let query1 = {'measures': [{'event_name': 'getPoint', 'aggregator': 'SUM', 'field': 'event.getPoint.pointNum'}], 
                    'unit': this.query.unit, 
                    'filter': this.filterList, 
                    'by_fields': ['event.getPoint.loginEnd'], 'sampling_factor': 64, 
                    'from_date': this.query.startData, 'to_date': this.query.endData, 
                    'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515755753844
                };
                let inforSent1 = {
                    query_id: 81,
                    real_time: true,
                    type: 'pie',
                    innerOrOut: 'inner',
                    query: query1
                };

                let query2 = {'measures': [{'event_name': 'getPoint', 'aggregator': 'SUM', 'field': 'event.getPoint.pointNum'}], 
                    'unit': this.query.unit, 
                    'filter': this.filterList, 'by_fields': ['event.getPoint.pointGetChannel'], 'sampling_factor': 64, 
                    'from_date': this.query.startData, 'to_date': this.query.endData,  
                    'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515755472671};
                let inforSent2 = {
                    query_id: 82,
                    real_time: true,
                    type: 'pie',
                    innerOrOut: 'outer',
                    query: query2
                };

                // 积分图表统计——获取对比图——获取角色
                this.chart2Loading = true;
                this.$store.dispatch('getQuery', inforSent1).then((data) => {
                    
                    let row1 = data.data.rollup_result.rows;
                    // 积分图表统计——获取对比图——获取途径
                    this.$store.dispatch('getQuery', inforSent2).then((data) => {
                        
                        this.chart2Loading = false;
                        let row2 = data.data.rollup_result.rows;
                      
                        let legendList = [];
                        let pieOuterList = [];
                        let pieInnerList = [];
                        
                        if (row1.length != 0) {
                            row1.forEach(function(item) {
                                legendList.push(item.by_values[0] || '未知');
                                pieInnerList.push({
                                    value: item.values[0][0],
                                    name: item.by_values[0] || '未知'
                                });
                            }, this);
                           
                            if (pieInnerList.length > 1) {
                                pieInnerList[1].selected = true;
                            }
                        }
                        
                        if (row2.length != 0) {
                            row2.forEach(function(item) {
                                legendList.push(item.by_values[0] || '未知');
                                pieOuterList.push({
                                    value: item.values[0][0],
                                    name: item.by_values[0] || '未知'
                                });
                            }, this);
                        }
                        
                        this.trendChart2Option = {
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} ({d}%)'
                            },
                            legend: {
                                orient: 'vertical',
                                x: 'left',
                                data: legendList// ['家长', '老师', '家长且老师', '签到', '充值', '礼物兑换', '发布作业', '发布动态', '活动奖励', '其他']
                            },
                            series: [
                                {
                                    name: '访问来源',
                                    type: 'pie',
                                    selectedMode: 'single',
                                    radius: [0, '35%'],
                                    color: ['#2EC7C9', '#B6A2DE', '#5AB1EF'],
                                    label: {
                                        normal: {
                                            position: 'inner'
                                        }
                                    },
                                    labelLine: {
                                        normal: {
                                            show: false
                                        }
                                    },
                                    data: pieInnerList
                                },
                                {
                                    name: '访问来源',
                                    type: 'pie',
                                    radius: ['50%', '75%'],
                                    color: ['#FFB980', '#DF9499', '#8D98B3', '#E5CF0D', '#97B552', '#95706D', '#DC69AA'],
                                    data: pieOuterList
                                }
                            ]
                        };
                    }).catch(() => {
                        this.chart2Loading = false;
                    });
                }).catch(() => {
                    this.chart2Loading = false;
                });
            },
            getTrendChart3() {
               
                // 积分消耗对比图——获取角色
                let query1 = {'measures': [{'event_name': 'productPurchase', 'aggregator': 'SUM', 'field': 'event.productPurchase.pointNum'}], 
                    'unit': this.query.unit, 
                    'filter': this.filterList, 'by_fields': ['event.productPurchase.loginEnd'], 'sampling_factor': 64, 
                    'from_date': this.query.startData, 'to_date': this.query.endData, 'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515762071277};
                let inforSent1 = {
                    query_id: 98,
                    real_time: true,
                    type: 'pie',
                    innerOrOut: 'inner',
                    query: query1
                };

                // 积分消耗对比图——获取途径
                let query2 = {'measures': [{'event_name': 'productPurchase', 'aggregator': 'SUM', 'field': 'event.productPurchase.pointNum'}], 
                    'unit': this.query.unit, 
                    'filter': this.filterList, 'by_fields': ['event.productPurchase.pointConsumeChannel'], 'sampling_factor': 64, 
                    'from_date': this.query.startData, 'to_date': this.query.endData, 'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515762017403};
                let inforSent2 = {
                    query_id: 99,
                    real_time: true,
                    type: 'pie',
                    innerOrOut: 'outer',
                    query: query2
                };

                // 积分消耗对比图——获取角色
                this.chart3Loading = true;
                this.$store.dispatch('getQuery', inforSent1).then((data) => {
                    let row1 = data.data.rollup_result.rows;
                     
                    // 积分消耗对比图——获取途径
                    this.$store.dispatch('getQuery', inforSent2).then((data) => {
                        this.chart3Loading = false;
                        let row2 = data.data.rollup_result.rows;
                        let legendList = [];
                        let pieOuterList = [];
                        let pieInnerList = [];

                        if (row1.length != 0) {
                            row1.forEach(function(item) {
                                legendList.push(item.by_values[0] || '未知');
                                pieInnerList.push({
                                    value: item.values[0][0],
                                    name: item.by_values[0] || '未知'
                                });
                            }, this);
                            if (pieInnerList.length > 1) {
                                pieInnerList[1].selected = true;
                            }
                        }
                        
                        if (row2.length != 0) {
                            row2.forEach(function(item) {
                                legendList.push(item.by_values[0] || '未知');
                                pieOuterList.push({
                                    value: item.values[0][0],
                                    name: item.by_values[0] || '未知'
                                });
                            }, this);
                        }
                        
                        this.trendChart3Option = {
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} ({d}%)'
                            },
                            legend: {
                                orient: 'vertical',
                                x: 'left',
                                data: legendList // ['家长', '老师', '家长且老师', '商品兑换', '礼物兑换', '勋章兑换']
                            },
                            series: [
                                {
                                    name: '访问来源',
                                    type: 'pie',
                                    selectedMode: 'single',
                                    radius: [0, '35%'],
                                    color: ['#2EC7C9', '#B6A2DE', '#5AB1EF'],
                                    label: {
                                        normal: {
                                            position: 'inner'
                                        }
                                    },
                                    labelLine: {
                                        normal: {
                                            show: false
                                        }
                                    },
                                    data: pieInnerList
                                },
                                {
                                    name: '访问来源',
                                    type: 'pie',
                                    radius: ['50%', '75%'],
                                    color: ['#FFB980', '#D87A80', '#8D98B3'],
                                    data: pieOuterList
                                }
                            ]
                        };
                    }).catch(() => {
                        this.chart3Loading = false;
                    });
                }).catch(() => {
                    this.chart3Loading = false;
                });
            }
        }
    }
</script>
<style lang="scss" scoped>
    .main-content {
        position: relative;
        $bgcolor: #fff;
    }
</style>                     